package com.weai.portal.controller;

import com.weai.portal.common.ApiResponse;
import com.weai.portal.entity.AiBooks;
import com.weai.portal.entity.TaskReport;
import com.weai.portal.service.TaskReportService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * AI清单控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/taskreport")
@RequiredArgsConstructor
@Tag(name = "任务AI周报", description = "AI自动评价需求进展")
public class TaskReportController {

    private final TaskReportService taskReportService;

    @GetMapping
    @Operation(summary = "获取AI周报清单列表", description = "获取所有AI任务周报")
    public ApiResponse<List<TaskReport>> list() {
        log.info("开始获取AI周报清单列表");
        try {
            List<TaskReport> taskReports = taskReportService.getAllAiReports();
            log.info("成功获取AI周报清单列表，数量: {}", taskReports.size());
            return ApiResponse.success(taskReports);
        } catch (Exception e) {
            log.error("获取AI清单列表失败", e);
            return ApiResponse.error(500, "获取AI周报清单列表失败");
        }
    }

    @GetMapping("/genreports")
    @Operation(summary = "生成AI周报清单列表", description = "手动触发生成所有AI任务周报")
    public ApiResponse<List<TaskReport>> genreports() {
        log.info("开始生成AI周报明细数据...");
        try {
            taskReportService.genAllAiReports();
            log.info("成功生成AI周报明细数据完成！");
            return ApiResponse.success();
        } catch (Exception e) {
            log.error("生成AI周报明细数据失败", e);
            return ApiResponse.error(500, "生成AI周报明细数据失败");
        }
    }
    
    @GetMapping("/exportexcel")
    @Operation(summary = "导出任务报告为Excel", description = "将当前周期的任务报告导出为Excel文件")
    public void exportToExcel(HttpServletResponse response) {
        log.info("开始导出任务报告为Excel");
        try {
            // 检查数据是否存在
            List<TaskReport> reports = taskReportService.getAllAiReports();
            if (reports.isEmpty()) {
                log.warn("导出Excel失败: 没有找到任务报告数据");
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write("{\"code\":400,\"message\":\"导出失败: 当前周期没有任务报告数据\"}");
                return;
            }
            
            taskReportService.exportToExcel(response);
            log.info("成功导出任务报告为Excel");
        } catch (Exception e) {
            log.error("导出Excel失败", e);
            // 这里不返回ApiResponse，因为输出流已经开始写入响应
            try {
                response.reset(); // 重置响应
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("{\"code\":500,\"message\":\"导出Excel失败: " + e.getMessage() + "\"}");
            } catch (Exception ex) {
                log.error("写入错误响应失败", ex);
            }
        }
    }
    
    @PostMapping("/generatehtml")
    @Operation(summary = "生成周报HTML", description = "生成当前周期的任务报告HTML格式")
    public ApiResponse<String> generateWeeklyHtml() {
        log.info("开始生成周报HTML");
        try {
            String html = taskReportService.generateWeeklyHtml();
            log.info("成功生成周报HTML");
            return ApiResponse.success(html);
        } catch (Exception e) {
            log.error("生成周报HTML失败", e);
            return ApiResponse.error(500, "生成周报HTML失败");
        }
    }

    @PostMapping("/savehtml")
    @Operation(summary = "保存周报HTML到服务器", description = "将生成的周报HTML保存到服务器指定目录")
    public ApiResponse<String> saveHtmlToServer(@RequestBody Map<String, String> request) {
        log.info("开始保存周报HTML到服务器");
        try {
            String htmlContent = request.get("htmlContent");
            if (htmlContent == null || htmlContent.isEmpty()) {
                return ApiResponse.error(400, "HTML内容不能为空");
            }
            
            String filePath = taskReportService.saveHtmlToServer(htmlContent);
            log.info("成功保存周报HTML到服务器: {}", filePath);
            return ApiResponse.success(filePath);
        } catch (Exception e) {
            log.error("保存周报HTML到服务器失败", e);
            return ApiResponse.error(500, "保存周报HTML到服务器失败: " + e.getMessage());
        }
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新任务报告", description = "更新指定ID的任务报告信息")
    public ApiResponse<TaskReport> updateTaskReport(@PathVariable Integer id, @RequestBody TaskReport taskReport) {
        log.info("开始更新任务报告，ID: {}", id);
        try {
            TaskReport updatedReport = taskReportService.updateTaskReport(id, taskReport);
            log.info("成功更新任务报告，ID: {}", id);
            return ApiResponse.success(updatedReport);
        } catch (Exception e) {
            log.error("更新任务报告失败，ID: {}", id, e);
            return ApiResponse.error(500, "更新任务报告失败: " + e.getMessage());
        }
    }
} 